<template>
  <div class="search-table">
    <!-- 筛选条件（可无） -->
    <a-row class="search-form" v-if="form">
      <slot name="searchForm"></slot>
      <a-row class="seach-btn-list" style="text-align: left">
        <a-form-item>
          <a-button
            type="primary"
            class="searchBtn"
            @click="handleSearch"
            :loading="tableLoading"
            >搜索</a-button
          >
          <a-button
            html-type="submit"
            class="resetBtn"
            @click="resetForm"
            :disabled="tableLoading"
            >重置</a-button
          >
        </a-form-item>
      </a-row>
    </a-row>
    <!-- 表格上面的操作（添加，导出等） -->
    <a-row class="opration-row" v-if="$slots.oprationRow">
      <slot name="oprationRow"></slot>
    </a-row>
    <a-row class="search-table-list">
      <div v-if="myTable">
        <slot
          name="myTable"
          :dataSource="dataSource"
          :pagination="pagination"
          :loading="tableLoading"
          :change="tableChange"
          :rowKey="rowKey"
          :row-selection="hideSelect ? null : rowSelection"
        ></slot>
      </div>
      <a-table
        v-else
        :rowKey="rowKey"
        :pagination="pagination"
        :loading="tableLoading"
        @change="tableChange"
        :row-selection="hideSelect ? null : rowSelection"
        :columns="columns"
        :data-source="dataSource"
        :scroll="{ x: xLength }"
      >
        <!-- 表格右侧的操作项 -->
        <span class="nowrap" slot="operation" slot-scope="text, record">
          <slot name="tableOperation" :record="record"></slot>
        </span>
        <template slot="changeSort" slot-scope="text, record, index">
          <div style="display: flex; justify-content: center">
            <a-icon
              type="arrow-up"
              style="margin-right: 10px; color: #1890ff; cursor: pointer"
              @click="moveUp(text, record, index)"
              v-if="index != 0"
            />
            <a-icon
              type="arrow-down"
              style="color: #ff7875; cursor: pointer"
              @click="moveDown(text, record, index)"
              v-if="!record.close"
            />
          </div>
        </template>
        <template slot="changeShow" slot-scope="text, record, index">
          <a-switch
            :defaultChecked="text == 1 ? true : false"
            @change="onChangeShow($event, record, index)"
          />
        </template>
      </a-table>
    </a-row>
  </div>
</template>
<script>
import Moment from "moment";

export default {
  name: "SearchTable",
  props: {
    url: {
      type: String,
      required: true,
    },
    hideSelect: {
      type: Boolean,
      required: false,
    },
    timeFormat: {
      // 搜索表单的时间格式化方式
      type: String,
      default: "YYYY-MM-DD HH:mm:ss",
    },
    defaultParams: {
      // 表格默认的参数，如果和搜索条件冲突，点击搜索时搜索条件会覆盖
      type: Object,
      default() {
        return {};
      },
    },
    initSearch: {
      // 默认刚进来就搜索,
      type: [Boolean, Promise],
      default: true,
    },
    beforeSearchFunc: {
      // 点击搜索对筛选参数二次处理
      type: Function,
    },
    rowKey: {
      // 表单唯一值，也是选中的时候的key值
      type: String,
      default: "id",
    },
    myTable: {
      // 使用页面自己的table组件
      type: Boolean,
      default: false,
    },
    // 是否显示分页组件
    pagination: {
      type: [Boolean, Object],
      default() {
        return {
          showQuickJumper: true,
          total: 0,
          current: 1,
          pageSize: 10,
          showTotal: (total) => `共${total}条`,
          showSizeChanger: true,
          pageSizeOptions: ["10", "20", "50", "100", "200"],
        };
      }
    },
    selectKeys: {
      type: Array,
    },
    form: {
      type: Object,
    },
    columns: {
      type: Array,
      required: true,
    },
    tableSelectType: {
      type: String,
      default: "checkbox",
    },
    xLength: {
      type: Number,
      default: 0,
    },
    beforeResetForm: {
      type: Function,
    },
    sortUrl: {
      type: String,
      default: "/gallery/classification/sort",
    },
    showUrl: {
      type: String,
      default: "/gallery/classification/update",
    },
  },
  data() {
    return {
      rowSelection: {
        type: this.tableSelectType,
        selectedRowKeys: [],
        onChange: (selectedRowKeys, selectedRows) => {
          this.rowSelection.selectedRowKeys = selectedRowKeys;
          this.selectedRowKeys = selectedRowKeys;
          this.selectedRows = selectedRows;
          this.$emit("selectedRowChange", selectedRows);
        },
      },
      searchParams: {},
      selectedRowKeys: [],
      selectedRows: [],
      size: 10,
      current: 1,
      dataSource: [],
      tableLoading: false,
      showValue: true,
    };
  },
  mounted() {
    if (typeof this.initSearch === "boolean" && this.initSearch) {
      this.handleSearch();
    } else if (this.initSearch instanceof Promise) {
      this.initSearch.then(() => {
        // initSearch返回resolve 的时候调用getList
        this.handleSearch();
      });
    }
  },
  methods: {
    tableChange(pagination) {
      if (pagination) {
        this.pagination.current = pagination.current;
        this.pagination.pageSize = pagination.pageSize;
        this.getList();
      }
    },
    // 点击重置
    resetForm() {
      if (this.beforeResetForm && this.beforeResetForm instanceof Function) {
        this.beforeResetForm();
      }
      this.form.resetFields();
      this.handleSearch();
    },
    // 刷新当前表格(外部页面可以调用这个方法刷新表格，比如删除或者修改状态之后刷新表格)
    refreshTable() {
      this.getFormValues().then((values) => {
        this.searchParams = {
          ...values,
        };
        this.getList();
      });
    },
    // 点击搜索
    handleSearch() {
      if(this.pagination) {
        this.pagination.current = 1;
      }
      this.getFormValues().then((values) => {
        this.searchParams = {
          ...values,
        };
        this.getList();
      });
    },
    // 获取筛选条件参数
    getFormValues() {
      return new Promise((resolve, reject) => {
        if (this.form) {
          this.form.validateFields((err, values) => {
            if (!err) {
              const timeFormat = this.timeFormat;
              Object.keys(values).forEach((key) => {
                // 除了时间和时间范围，其他特殊情况请使用beforeSearchFunc处理
                if (values[key] instanceof Moment) {
                  // 选择时间
                  values[key] = values[key].format(timeFormat);
                } else if (
                  key.split("-").length === 2 &&
                  Array.isArray(values[key])
                ) {
                  // 选择时间范围
                  const arr = key.split("-");
                  values[arr[0]] = values[key][0];
                  values[arr[1]] = values[key][1];
                  delete values[key];
                }
              });
              if (this.beforeSearchFunc) {
                values = this.beforeSearchFunc(values);
              }
              resolve(values);
            }
          });
        } else {
          // 该表单没有筛选条件表单
          resolve({});
        }
      });
    },
    // 请求接口获取列表数据
    getList() {
      if (!this.url) return;
      let pageParams = {}
      if(this.pagination) {
        pageParams.current = this.pagination.current
        pageParams.size = this.pagination.pageSize
      }
      this.searchParams = {
        ...this.defaultParams,
        ...this.searchParams, // 搜索条件可以覆盖默认参数
        ...pageParams,
      };
      this.tableLoading = true;
      this.$get(this.url, this.searchParams, { preventLoading: true })
        .then((res) => {
          this.tableLoading = false;
          if (res && res.returnCode === 1000) {
            this.selectedRowKeys = [];
            this.selectedRows = [];
            this.rowSelection.selectedRowKeys = [];
            this.dataSource = res.dataInfo || [];
            // this.dataSource.sort((a, b) => {
            //   return a.sort - b.sort;
            // });
            console.log(this.dataSource);
            this.dataSource[this.dataSource.length - 1].close = true;
            this.dataSource.forEach((item) => {
              if (item.children.length > 0) {
                item.children[item.children.length - 1].close = true;
              }
            });
            if(this.pagination){
              this.pagination.total = res.dataInfo.total;
            }
            this.$emit("dataSourceChange", res.dataInfo);
            this.$emit("selectedRowChange", this.selectedRows);
          } else {
            this.dataSource = [];
          }
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },

    async changeSort(params) {
      let res = await this.$post(this.sortUrl, params);
      if (res && res.returnCode == 1000) {
        console.log(res);
      }
    },
    // async changeSort1() {
    //   let arr = this.dataSource;
    //   let params = [];
    //   arr.forEach((l, i) => {
    //     params.push({
    //       id: l.id,
    //       sort: i + 1,
    //     });
    //   });
    //   let res = await this.$post("/gallery/classificationpublish/sort", params);
    //   if (res && res.returnCode == 1000) {
    //     console.log(res);
    //   }
    // },
    async changeShow(params) {
      let res = await this.$post(this.showUrl, params);
      if (res && res.returnCode == 1000) {
        console.log(res);
      }
    },
    moveUp(text, record, index) {
      // console.log(this.dataSource[index - 1]);
      // this.changeSort1()
      console.log(record, index);
      const aobj = [];
      this.dataSource.forEach((item) => {
        aobj.push(item.sort);
      });
      let arr = [];
      if (record.classifyLevel == 1) {
        arr = JSON.parse(JSON.stringify(this.dataSource));
        let params = [
          {
            id: record.id,
            sort: record.sort * 1 - 1,
          },
          {
            id: this.dataSource[index - 1].id,
            sort: this.dataSource[index - 1].sort * 1 + 1,
          },
        ];
        let newArr = this.swapItems(arr, index, index - 1);
        this.changeSort(params);
        this.dataSource = newArr;
        this.dataSource.forEach((item, i) => {
          item.sort = i + 1;
        });
        this.dataSource.forEach((item) => {
          item.close = false;
          if (item.children.length > 0) {
            item.children.forEach((l) => {
              l.close = false;
            });
            item.children[item.children.length - 1].close = true;
          }
        });
        this.dataSource[this.dataSource.length - 1].close = true;
      } else {
        if(record.classifyLevel == 2) {
          this.moveUpFun(this.dataSource, record, index)
        } else if(record.classifyLevel == 3) {
          let grandParentRes = this.dataSource.filter(item => {
            return record.parentIds.includes(item.id)
          })
          this.moveUpFun(grandParentRes[0].children, record, index)
        }
      }
    },
    moveUpFun(data, record, index) {
      console.log(data)
      let arr = [];
      data.forEach((item) => {
        if (
          record.parentId == item.id ||
          record.parentId == item.galleryClassificationId
        ) {
          arr = item.children;
        }
      });
      console.log(arr)
      let params = [
        {
          id: record.id,
          sort: record.sort * 1 - 1,
        },
        {
          id: arr[index - 1].id,
          sort: arr[index - 1].sort * 1 + 1,
        },
      ];
      // arr[index].sort = arr[index].sort * 1 - 1;
      // arr[index - 1].sort = arr[index - 1].sort * 1 + 1;
      this.changeSort(params);
      let newArr = this.swapItems(arr, index, index - 1);
      newArr.forEach((item, i) => {
        item.sort = i + 1;
      });
      data.forEach((item) => {
        if (record.parentId == item.id) {
          item = newArr;
        }
      });
      data.forEach((item) => {
        item.close = false;
        if (item.children.length > 0) {
          item.children.forEach((l) => {
            l.close = false;
          });
          item.children[item.children.length - 1].close = true;
        }
      });
      data[data.length - 1].close = true;
    },
    moveDown(text, record, index) {
      let arr1 = [];
      if (record.classifyLevel == 1) {
        arr1 = JSON.parse(JSON.stringify(this.dataSource));
        let params = [
          {
            id: record.id,
            sort: record.sort * 1 + 1,
          },
          {
            id: this.dataSource[index + 1].id,
            sort: this.dataSource[index + 1].sort * 1 - 1,
          },
        ];
        // this.dataSource[index].sort = this.dataSource[index].sort * 1 + 1;
        // this.dataSource[index + 1].sort =
        //   this.dataSource[index + 1].sort * 1 - 1;
        this.changeSort(params);
        let newArr = this.swapItems(arr1, index, index + 1);
        this.dataSource = newArr;
        this.dataSource.forEach((item, i) => {
          item.sort = i + 1;
        });
        this.dataSource.forEach((item) => {
          item.close = false;
          if (item.children.length > 0) {
            item.children.forEach((l) => {
              l.close = false;
            });
            item.children[item.children.length - 1].close = true;
          }
        });
        this.dataSource[this.dataSource.length - 1].close = true;
      } else {
        if(record.classifyLevel == 2) {
          this.moveDownFun(this.dataSource, record, index)
        } else if(record.classifyLevel == 3) {
          let grandParentRes = this.dataSource.filter(item => {
            return record.parentIds.includes(item.id)
          })
          this.moveDownFun(grandParentRes[0].children, record, index)
        }
      }
    },
    moveDownFun(data, record, index) {
      let arr1 = [];
      data.forEach((item) => {
        if (
          record.parentId == item.id ||
          record.parentId == item.galleryClassificationId
        ) {
          arr1 = item.children;
        }
      });
      let params = [
        {
          id: record.id,
          sort: record.sort * 1 + 1,
        },
        {
          id: arr1[index + 1].id,
          sort: arr1[index + 1].sort * 1 - 1,
        },
      ];
      // arr1[index].sort = arr1[index].sort * 1 + 1;
      // arr1[index + 1].sort = arr1[index + 1].sort * 1 - 1;
      this.changeSort(params);
      let newArr = this.swapItems(arr1, index, index + 1);
      newArr.forEach((item, i) => {
        item.sort = i + 1;
      });
      data.forEach((item) => {
        if (record.parentId == item.id) {
          item = newArr;
        }
      });
      data.forEach((item) => {
        item.close = false;
        if (item.children.length > 0) {
          item.children.forEach((l) => {
            l.close = false;
          });
          item.children[item.children.length - 1].close = true;
        }
      });
      data[data.length - 1].close = true;
    },
    swapItems(arr, index1, index2) {
      arr[index1] = arr.splice(index2, 1, arr[index1])[0];
      return arr;
    },
    onChangeShow($event, record, index) {
      if ($event == true) {
        this.showValue = 1;
      } else if ($event == false) {
        this.showValue = 0;
      }
      this.changeShow({
        id: record.id,
        enableShow: this.showValue,
      });
    },
  },
};
</script>
<style lang="less" scoped>
.search-table {
  .search-form {
    border-radius: 4px;
    background-color: #f5f5f5;
    padding: 24px 32px;
    .ant-form-item {
      margin-bottom: 0;
    }
    .seach-btn-list {
      .ant-btn {
        margin-right: 20px;
        margin-top: 20px;
      }
    }
  }
  .opration-row {
    padding-top: 32px;
    /deep/.ant-btn {
      margin-right: 20px;
    }
  }
  .search-table-list {
    margin-top: 16px;
    .ant-table {
      .ant-table-body {
        .ant-table-thead {
          tr {
            th {
              font-weight: bold;
            }
          }
        }
      }
    }
  }
}
.flip-list-move {
  transition: transform 0.5s;
}
</style>
